/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package shop;
import java.util.*;

abstract class User {
    protected String userID;
    protected String username;
    protected String password;
    protected String email;
    protected String phoneNumber;

    public User(String userID, String username, String password, String email, String phoneNumber) {
        this.userID = userID;
        this.username = username;
        this.password = password;
        this.email = email;
        this.phoneNumber = phoneNumber;
    }

    public String getUserID() {
        return userID;
    }

    public String getUsername() {
        return username;
    }

    public abstract void login();
    public abstract void changePassword();
}

class Admin extends User {
    private static final String DEFAULT_ADMIN_PASSWORD = "ynuadmin";
    private String adminPassword = DEFAULT_ADMIN_PASSWORD;

    public Admin(String userID, String username, String email, String phoneNumber) {
        super(userID, username, DEFAULT_ADMIN_PASSWORD, email, phoneNumber);
    }

    @Override
    public void login() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入管理员密码: ");
        String inputPassword = scanner.nextLine();

        if (adminPassword.equals(inputPassword)) {
            System.out.println("登录成功!");
        } else {
            System.out.println("密码错误!");
        }
    }

    @Override
    public void changePassword() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入新密码: ");
        String newPassword = scanner.nextLine();
        this.adminPassword = newPassword;
        System.out.println("密码修改成功!");
    }

    public void resetCustomerPassword(Customer customer) {
        customer.setPassword("default123");  // 重置密码为默认值
        System.out.println("用户 " + customer.getUsername() + " 的密码已重置为默认值。");
    }

    public void viewAllCustomers(List<Customer> customers) {
        for (Customer customer : customers) {
            System.out.println(customer);
        }
    }

    public void deleteCustomer(List<Customer> customers, String customerID) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("警告: 你正在删除客户信息，操作不可恢复。确认继续？(y/n)");
        String confirmation = scanner.nextLine();
        if ("y".equalsIgnoreCase(confirmation)) {
            customers.removeIf(customer -> customer.getUserID().equals(customerID));
            System.out.println("客户删除成功。");
        } else {
            System.out.println("删除操作已取消。");
        }
    }

    public void searchCustomer(List<Customer> customers, String query) {
        for (Customer customer : customers) {
            if (customer.getUserID().equals(query) || customer.getUsername().equals(query)) {
                System.out.println(customer);
                return;
            }
        }
        System.out.println("未找到符合条件的客户。");
    }

    public void viewAllProducts(List<Product> products) {
        for (Product product : products) {
            System.out.println(product);
        }
    }

    public void addProduct(List<Product> products, Product product) {
        for (Product p : products) {
            if (p.getProductID().equals(product.getProductID())) {
                System.out.println("商品编号已存在，添加失败。");
                return;
            }
        }
        products.add(product);
        System.out.println("商品添加成功。");
    }

    public void updateProduct(Product product, String name, String manufacturer, double price, int quantity) {
        product.setName(name);
        product.setManufacturer(manufacturer);
        product.setPrice(price);
        product.setQuantity(quantity);
        System.out.println("商品信息更新成功。");
    }

    public void deleteProduct(List<Product> products, String productID) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("警告: 你正在删除商品信息，操作不可恢复。确认继续？(y/n)");
        String confirmation = scanner.nextLine();
        if ("y".equalsIgnoreCase(confirmation)) {
            products.removeIf(product -> product.getProductID().equals(productID));
            System.out.println("商品删除成功。");
        } else {
            System.out.println("删除操作已取消。");
        }
    }
}

class Customer extends User {
    private String level;
    private Date registrationDate;
    private double totalSpent;
    private List<Product> shoppingCart = new ArrayList<>();
    private List<Purchase> purchaseHistory = new ArrayList<>();

    public Customer(String userID, String username, String password, String email, String phoneNumber, String level, Date registrationDate) {
        super(userID, username, password, email, phoneNumber);
        this.level = level;
        this.registrationDate = registrationDate;
        this.totalSpent = 0.0;
    }

    public void setPassword(String newPassword) {
        this.password = newPassword;
    }

    @Override
    public void login() {
        Scanner scanner = new Scanner(System.in);
        int attempts = 0;
        while (attempts < 5) {
            System.out.print("请输入密码: ");
            String inputPassword = scanner.nextLine();

            if (password.equals(inputPassword)) {
                System.out.println("登录成功!");
                return;
            } else {
                attempts++;
                System.out.println("密码错误! 您还有 " + (5 - attempts) + " 次机会。");
            }
        }
        System.out.println("账户已锁定，请稍后再试。");
    }

    @Override
    public void changePassword() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入新密码: ");
        String newPassword = scanner.nextLine();
        if (isValidPassword(newPassword)) {
            this.password = newPassword;
            System.out.println("密码修改成功!");
        } else {
            System.out.println("密码不符合要求，请重新输入。");
        }
    }

    public void resetPassword() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入用户名: ");
        String inputUsername = scanner.nextLine();
        System.out.print("请输入注册邮箱: ");
        String inputEmail = scanner.nextLine();

        if (this.username.equals(inputUsername) && this.email.equals(inputEmail)) {
            String newPassword = generateRandomPassword();
            this.password = newPassword;
            System.out.println("新密码已发送至您的邮箱: " + inputEmail);
            // 模拟发送邮件
            System.out.println("新密码为: " + newPassword);
        } else {
            System.out.println("用户名或邮箱不匹配。");
        }
    }

    public void addToCart(Product product, int quantity) {
        for (Product p : shoppingCart) {
            if (p.getProductID().equals(product.getProductID())) {
                p.setQuantity(p.getQuantity() + quantity);
                System.out.println("购物车中已更新商品数量。");
                return;
            }
        }
        Product cartProduct = new Product(product.getProductID(), product.getName(), product.getManufacturer(),
                                          product.getManufactureDate(), product.getPrice(), quantity);
        shoppingCart.add(cartProduct);
        System.out.println("商品已添加到购物车。");
    }

    public void removeFromCart(String productID) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("确认移除商品？(y/n)");
        String confirmation = scanner.nextLine();
        if ("y".equalsIgnoreCase(confirmation)) {
            shoppingCart.removeIf(product -> product.getProductID().equals(productID));
            System.out.println("商品已从购物车中移除。");
        } else {
            System.out.println("移除操作已取消。");
        }
    }

    public void updateCart(String productID, int quantity) {
        for (Product product : shoppingCart) {
            if (product.getProductID().equals(productID)) {
                if (quantity > 0) {
                    product.setQuantity(quantity);
                } else {
                    shoppingCart.remove(product);
                }
                break;
            }
        }
        System.out.println("购物车已更新。");
    }

    public void checkout(List<Product> products) {
        double total = 0.0;
        for (Product cartItem : shoppingCart) {
            for (Product storeItem : products) {
                if (storeItem.getProductID().equals(cartItem.getProductID())) {
                    if (storeItem.getQuantity() >= cartItem.getQuantity()) {
                        storeItem.setQuantity(storeItem.getQuantity() - cartItem.getQuantity());
                        total += cartItem.getPrice() * cartItem.getQuantity();
                    } else {
                        System.out.println("库存不足，无法购买商品: " + cartItem.getName());
                        return;
                    }
                }
            }
        }
        totalSpent += total;
        purchaseHistory.add(new Purchase(new Date(), new ArrayList<>(shoppingCart), total));
        shoppingCart.clear();
        System.out.println("支付成功，总金额为: " + total + "元。");
    }

    public void viewPurchaseHistory() {
        for (Purchase purchase : purchaseHistory) {
            System.out.println(purchase);
        }
    }

    private boolean isValidPassword(String password) {
        return password.length() > 8 && password.matches(".*[A-Z].*") && password.matches(".*[a-z].*")
                && password.matches(".*\\d.*") && password.matches(".*[!@#\\$%\\^&\\*].*");
    }

    private String generateRandomPassword() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
        StringBuilder password = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            password.append(chars.charAt(random.nextInt(chars.length())));
        }
        return password.toString();
    }

    @Override
    public String toString() {
        return "客户ID: " + userID + ", 用户名: " + username + ", 级别: " + level + ", 注册时间: " + registrationDate
                + ", 累计消费: " + totalSpent + ", 手机号: " + phoneNumber + ", 邮箱: " + email;
    }
}

class Product {
    private String productID;
    private String name;
    private String manufacturer;
    private Date manufactureDate;
    private double price;
    private int quantity;

    public Product(String productID, String name, String manufacturer, Date manufactureDate, double price, int quantity) {
        this.productID = productID;
        this.name = name;
        this.manufacturer = manufacturer;
        this.manufactureDate = manufactureDate;
        this.price = price;
        this.quantity = quantity;
    }

    public String getProductID() {
        return productID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public void setManufacturer(String manufacturer) {
        this.manufacturer = manufacturer;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    // 添加 getManufactureDate 方法
    public Date getManufactureDate() {
        return manufactureDate;
    }

    @Override
    public String toString() {
        return "商品编号: " + productID + ", 名称: " + name + ", 制造商: " + manufacturer + ", 价格: " + price + ", 数量: " + quantity;
    }
}

class Purchase {
    private Date purchaseDate;
    private List<Product> products;
    private double totalAmount;

    public Purchase(Date purchaseDate, List<Product> products, double totalAmount) {
        this.purchaseDate = purchaseDate;
        this.products = products;
        this.totalAmount = totalAmount;
    }

    @Override
    public String toString() {
        return "购买日期: " + purchaseDate + ", 总金额: " + totalAmount;
    }
}

public class shop {
    private static List<Customer> customers = new ArrayList<>();
    private static List<Product> products = new ArrayList<>();

    public static void main(String[] args) {
        Admin admin = new Admin("1", "admin", "admin@ynu.edu.cn", "123456789");
        initializeSystem(); // 初始化一些数据

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("1. 管理员登录");
            System.out.println("2. 客户注册");
            System.out.println("3. 客户登录");
            System.out.println("4. 退出");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 吸收换行符

            switch (choice) {
                case 1:
                    admin.login();
                    adminMenu(admin, scanner);
                    break;
                case 2:
                    registerCustomer(scanner);
                    break;
                case 3:
                    customerLogin(scanner);
                    break;
                case 4:
                    System.out.println("系统退出。");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private static void adminMenu(Admin admin, Scanner scanner) {
        while (true) {
            System.out.println("1. 查看所有客户信息");
            System.out.println("2. 删除客户");
            System.out.println("3. 查询客户信息");
            System.out.println("4. 查看所有商品信息");
            System.out.println("5. 添加商品");
            System.out.println("6. 修改商品信息");
            System.out.println("7. 删除商品");
            System.out.println("8. 修改管理员密码");
            System.out.println("9. 返回主菜单");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 吸收换行符

            switch (choice) {
                case 1:
                    admin.viewAllCustomers(customers);
                    break;
                case 2:
                    System.out.print("请输入要删除的客户ID: ");
                    String customerID = scanner.nextLine();
                    admin.deleteCustomer(customers, customerID);
                    break;
                case 3:
                    System.out.print("请输入客户ID或用户名: ");
                    String query = scanner.nextLine();
                    admin.searchCustomer(customers, query);
                    break;
                case 4:
                    admin.viewAllProducts(products);
                    break;
                case 5:
                    addProduct(scanner);
                    break;
                case 6:
                    updateProduct(scanner);
                    break;
                case 7:
                    System.out.print("请输入要删除的商品ID: ");
                    String productID = scanner.nextLine();
                    admin.deleteProduct(products, productID);
                    break;
                case 8:
                    admin.changePassword();
                    break;
                case 9:
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private static void registerCustomer(Scanner scanner) {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();
        System.out.print("请输入邮箱: ");
        String email = scanner.nextLine();
        System.out.print("请输入手机号: ");
        String phoneNumber = scanner.nextLine();

        if (password.length() < 8 || !password.matches(".*[A-Z].*") || !password.matches(".*[a-z].*")
                || !password.matches(".*\\d.*") || !password.matches(".*[!@#\\$%\\^&\\*].*")) {
            System.out.println("密码不符合要求，请重新注册。");
            return;
        }

        String customerID = "C" + (customers.size() + 1);
        Customer newCustomer = new Customer(customerID, username, password, email, phoneNumber, "铜牌客户", new Date());
        customers.add(newCustomer);
        System.out.println("注册成功，您的客户ID为: " + customerID);
    }

    private static void customerLogin(Scanner scanner) {
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        for (Customer customer : customers) {
            if (customer.getUsername().equals(username)) {
                if (customer.password.equals(password)) {
                    System.out.println("登录成功!");
                    customerMenu(customer, scanner);  // 登录成功后进入菜单
                    return;
                } else {
                    System.out.println("密码错误!");
                }
            }
        }
        System.out.println("未找到该用户，请检查用户名和密码是否正确。");
    }

    private static void customerMenu(Customer customer, Scanner scanner) {
        while (true) {
            System.out.println("1. 修改密码");
            System.out.println("2. 忘记密码");
            System.out.println("3. 查看商品");
            System.out.println("4. 添加商品到购物车");
            System.out.println("5. 移除购物车中的商品");
            System.out.println("6. 修改购物车中的商品数量");
            System.out.println("7. 结账");
            System.out.println("8. 查看购物历史");
            System.out.println("9. 返回主菜单");
            System.out.print("请选择操作: ");
            int choice = scanner.nextInt();
            scanner.nextLine(); // 吸收换行符

            switch (choice) {
                case 1:
                    customer.changePassword();
                    break;
                case 2:
                    customer.resetPassword();
                    break;
                case 3:
                    for (Product product : products) {
                        System.out.println(product);
                    }
                    break;
                case 4:
                    addToCart(customer, scanner);
                    break;
                case 5:
                    removeFromCart(customer, scanner);
                    break;
                case 6:
                    updateCart(customer, scanner);
                    break;
                case 7:
                    customer.checkout(products);
                    break;
                case 8:
                    customer.viewPurchaseHistory();
                    break;
                case 9:
                    return;
                default:
                    System.out.println("无效的选择，请重新输入。");
            }
        }
    }

    private static void addProduct(Scanner scanner) {
        System.out.print("请输入商品编号: ");
        String productID = scanner.nextLine();
        System.out.print("请输入商品名称: ");
        String name = scanner.nextLine();
        System.out.print("请输入制造商: ");
        String manufacturer = scanner.nextLine();
        System.out.print("请输入制造日期 (yyyy-MM-dd): ");
        String dateString = scanner.nextLine();
        System.out.print("请输入价格: ");
        double price = 0;
        try {
            price = scanner.nextDouble();
        } catch (InputMismatchException e) {
            System.out.println("请输入有效的价格。");
            return;
        }
        System.out.print("请输入数量: ");
        int quantity = 0;
        try {
            quantity = scanner.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("请输入有效的数量。");
            return;
        }
        scanner.nextLine(); // 吸收换行符

        Date manufactureDate = null;
        try {
            manufactureDate = new Date(dateString);
        } catch (Exception e) {
            System.out.println("日期格式错误。");
            return;
        }

        Product product = new Product(productID, name, manufacturer, manufactureDate, price, quantity);
        products.add(product);
        System.out.println("商品添加成功。");
    }

    private static void updateProduct(Scanner scanner) {
        System.out.print("请输入要修改的商品编号: ");
        String productID = scanner.nextLine();

        for (Product product : products) {
            if (product.getProductID().equals(productID)) {
                System.out.print("请输入新商品名称: ");
                String name = scanner.nextLine();
                System.out.print("请输入新制造商: ");
                String manufacturer = scanner.nextLine();
                System.out.print("请输入新价格: ");
                double price = 0;
                try {
                    price = scanner.nextDouble();
                } catch (InputMismatchException e) {
                    System.out.println("请输入有效的价格。");
                    return;
                }
                System.out.print("请输入新数量: ");
                int quantity = 0;
                try {
                    quantity = scanner.nextInt();
                } catch (InputMismatchException e) {
                    System.out.println("请输入有效的数量。");
                    return;
                }
                scanner.nextLine(); // 吸收换行符

                product.setName(name);
                product.setManufacturer(manufacturer);
                product.setPrice(price);
                product.setQuantity(quantity);

                System.out.println("商品信息更新成功。");
                return;
            }
        }
        System.out.println("未找到商品，无法更新。");
    }

    private static void addToCart(Customer customer, Scanner scanner) {
        System.out.print("请输入要添加到购物车的商品编号: ");
        String productID = scanner.nextLine();
        System.out.print("请输入要购买的数量: ");
        int quantity = 0;
        try {
            quantity = scanner.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("请输入有效的数量。");
            return;
        }
        scanner.nextLine(); // 吸收换行符

        for (Product product : products) {
            if (product.getProductID().equals(productID)) {
                customer.addToCart(product, quantity);
                return;
            }
        }
        System.out.println("未找到商品，无法添加到购物车。");
    }

    private static void removeFromCart(Customer customer, Scanner scanner) {
        System.out.print("请输入要从购物车中移除的商品编号: ");
        String productID = scanner.nextLine();
        customer.removeFromCart(productID);
    }

    private static void updateCart(Customer customer, Scanner scanner) {
        System.out.print("请输入要修改的商品编号: ");
        String productID = scanner.nextLine();
        System.out.print("请输入新数量: ");
        int quantity = 0;
        try {
            quantity = scanner.nextInt();
        } catch (InputMismatchException e) {
            System.out.println("请输入有效的数量。");
            return;
        }
        scanner.nextLine(); // 吸收换行符
        customer.updateCart(productID, quantity);
    }

    private static void initializeSystem() {
    
        products.add(new Product("001", "商品1", "厂家A", new Date(), 100.0, 10));
        products.add(new Product("002", "商品2", "厂家B", new Date(), 150.0, 5));

        customers.add(new Customer("C1", "user1", "Password123!", "user1@ynu.edu.cn", "123456789", "金牌客户", new Date()));
        customers.add(new Customer("C2", "user2", "Password123!", "user2@ynu.edu.cn", "987654321", "银牌客户", new Date()));
    }
}